package com.example.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.example.demo.common.Result;
import com.example.demo.entity.WebPage4User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${server.port}")
    private String port;
    private static final String ip="http://localhost";
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file) throws IOException {
        String originalFilename=file.getOriginalFilename();
        String flag= IdUtil.fastSimpleUUID();
        String rootFilePath= System.getProperty("user.dir")+"/springboot/src/main/resources/files/"+flag+"_"+originalFilename;
        FileUtil.writeBytes(file.getBytes(),rootFilePath);
        return Result.success(ip+":"+port+"/files/"+flag);
    }
    @PostMapping("/cover")
    public WebPage4User coverUpload( MultipartFile file) throws IOException{
        byte[] bytes = file.getBytes();
        WebPage4User webPage4User=new WebPage4User();
        webPage4User.setUrlurl(bytes);
        return webPage4User;
    }

    @PostMapping("/editor/upload")
    public JSON editorUpload(MultipartFile file) throws IOException {
        String originalFilename=file.getOriginalFilename();
        String flag= IdUtil.fastSimpleUUID();
        String rootFilePath= System.getProperty("user.dir")+"/springboot/src/main/resources/files/"+flag+"_"+originalFilename;
        FileUtil.writeBytes(file.getBytes(),rootFilePath);
        String url=ip+":"+port+"/files/"+flag;
        JSONObject json=new JSONObject();
        json.set("errno",0);
        JSONArray arr=new JSONArray();
        JSONObject data=new JSONObject();
        arr.add(data);
        data.set("url",url);
        json.set("data",arr);
        return json;
    }
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag,HttpServletResponse response){
        OutputStream os;
//        文件上传的跟路径
        String basePath=System.getProperty("user.dir")+"/springboot/src/main/resources/files/";
        List<String> fileNames=FileUtil.listFileNames(basePath);
//        找到参数一致的文件
        String avatar=fileNames.stream().filter(name->name.contains(flag)).findAny().orElse("");
        try {
            if(StrUtil.isNotEmpty(avatar)){
                response.addHeader("Content-Disposition","attachment;filename="+
                        URLEncoder.encode(avatar,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes=FileUtil.readBytes(basePath+avatar);//读取字节流
                os=response.getOutputStream();//通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        }catch (Exception e){
            System.out.println("文件不存在");
        }
    }
}
